package com.lifang.imgsoa.client;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.leo.jackson.JsonTool;
import com.lifang.client.BaseClient;
import com.lifang.imgsoa.model.ImageKeyObject;
import com.lifang.imgsoa.model.Response;
import com.lifang.model.enums.AppEnum;

public class HuigouImgSOAClient extends BaseClient
{

    protected static final Logger logger = Logger.getLogger(HuigouImgSOAClient.class);

    public HuigouImgSOAClient(String serverURL)
    {
        super(serverURL);
    }

    public HuigouImgSOAClient(String serverURL, int soTimeout)
    {
        super(serverURL, soTimeout);
    }
    
    
    /**
     * @date 2014年10月15日 下午3:05:16
     * @author Tom
     * @description 上传图片
     * @param isMakeOriginal
     *            //是否对原图进行处理 1处理，0 不处理
     * @param fileBytes
     *            //图片的byte数组
     */
    public ImageKeyObject uploadSingleFile(byte[] fileBytes) {
        if (fileBytes == null || fileBytes.length == 0) {
            logger.error("参数：fileBytes:错误，请检测！");
            return null;
        }
        Map<String, Object> params = new HashMap<String, Object>();
        try {
            params.put("fileBytes", new String(fileBytes, "ISO8859-1"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String html = httpPost(params);

        return getData2Object(html, ImageKeyObject.class);

    }
    
    protected <T> T getData2Object(String returnStr, Class<T> clazz) {

        if (StringUtils.isBlank(returnStr)) {
            logger.error("服务器ImgSOA异常：returnStr:{" + returnStr + "}");

            return null;
        }

        try {
            JSONObject json = JSONObject.fromObject(returnStr);
            int status = json.getInt("status");

            if (status != 1) {
                logger.info("调用ImgSOA 接口异常：returnStr:{" + returnStr + "}");
                return null;
            }

            String dataJson = json.getString("data");
            return JsonTool.readValue(dataJson, clazz);

        } catch (Exception e) {
            logger.error("ImgSOA返回数据，解析json错误:{" + returnStr + "}", e);
            return null;
        }
    }

    public static void main(String[] args) throws IOException
    {

    }
}
